<template>
  <div>
    <el-dialog title="选择题目" :visible="true" width="880px" top="10px" :close-on-click-modal="false" :before-close="close">
      <el-form ref="searchTopic" :inline="true" :model="search" size="mini">
        <el-form-item label="所属题库">
          <el-select v-model="search.bank" placeholder="请选择">
            <el-option
              v-for="item in options.bank"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="知识点"><edu-cascader :value.sync="cascader.point" :options="options.point" :args="{}" /></el-form-item>
        <el-form-item label="题目类型"><edu-select :value.sync="search.question_type" :options="options.questionType" :args="{}" /></el-form-item>
        <el-form-item label="难易度"><edu-select :value.sync="search.difficulty" :options="options.difficulty" :args="{}" /></el-form-item>
        <el-form-item label="题目名称"><el-input v-model="search.title" placeholder="请输入题目名称关键字" /></el-form-item>
        <el-form-item><el-button @click="loadTopic">搜索</el-button></el-form-item>
      </el-form>
      <div>
        <el-table ref="topicTable" v-loading.lock="loading" :data="datas" style="width: 100%" height="400" row-key="id" @selection-change="handleSelectChange">
          <el-table-column type="selection" min-width="50" :selectable="checkSelectable" />
          <el-table-column label="题干">
            <template slot-scope="scope">
              <topic-title :row="scope.row" />
            </template>
          </el-table-column>
          <el-table-column prop="question_type_text" label="题型" width="180" />
          <el-table-column prop="difficulty_title" label="难易度" />
          <el-table-column prop="point_str" label="知识点" />
        </el-table>
        <el-pagination :current-page.sync="paginate.page" :page-size="paginate.count" layout="total, prev, pager, next" :total="total" @current-change="handleCurrentChange" />
      </div>
      <div slot="footer" class="choose-footer">
        <el-button type="primary" size="small" @click="choose">确认</el-button>
        <el-button size="small" @click="close">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import EduSelect from '@public/form/select.vue';
import EduCascader from '@public/form/cascader.vue';
import TopicTitle from '../components/title.vue';
import { mapGetters } from 'vuex';
export default {
  components: {
    EduSelect,
    EduCascader,
    TopicTitle
  },
  props: {
    partIndex: {
      type: Number,
      required: true
    },
    cateIds: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      search: {
        bank: '',
        point: '',
        question_type: '',
        difficulty: '',
        title: ''
      },
      cascader: {},
      topics: [],
      options: {
        bank: [],
        point: [],
        questionType: [],
        difficulty: []
      },
      paginate: {
        count: 10,
        page: 1
      },
      response: null,
      loading: true
    };
  },
  computed: {
    datas() {
      if (this.response) {
        return this.response.data.datas;
      }
      return [];
    },
    total() {
      if (this.response) {
        return this.response.data.paginate.total;
      }
      return 0;
    },
    ...mapGetters({
      parts: 'examPaper/settled/parts'
    })
  },
  watch: {
    cascader: {
      handler(datas) {
        Object.keys(datas).forEach(key => {
          const value = datas[key];
          const [val] = [...value].reverse();
          this.$set(this.search, key, val);
        });
      },
      deep: true
    }
  },
  created() {
    this.loadOptions();
    this.loadTopic();
  },
  methods: {
    close() {
      this.$emit('close');
    },
    choose() {
      const part = this.parts[this.partIndex];
      const { scores, topics } = part;
      const newTopics = [...topics];
      const addNewTopicIds = [];
      this.topics.forEach(topic => {
        // 检测是否已经选中了该试题
        if (this.checkSelectable(topic)) {
          const score = scores['question_type_' + topic.question_type] || 1;
          // 材料题下面的试题添加分数字段
          if (topic.question_type == 6 || topic.question_type == 7) {
            topic.options.forEach(item => {
              item.score = 1;
            });
          }
          newTopics.push({
            checked: false,
            score: score,
            topic
          });
          addNewTopicIds.push(topic.id);
        }
      });
      this.$store.dispatch('examPaper/settled/setPart', {
        partIndex: this.partIndex,
        data: {
          ...part,
          topics: newTopics
        }
      });

      this.$store.dispatch('examPaper/settled/settingTopicScores', {
        partIndex: this.partIndex,
        topicIds: addNewTopicIds
      });

      this.$emit('close');
    },

    loadOptions() {
      var param = {};
      if (this.cateIds) {
        param = { cate: this.cateIds };
      }
      // console.log(param);
      this.$http.get(
        '/exam/admin/question/topic/choose/options',
        param,
        response => {
          const {
            data: { options }
          } = response;
          this.options = options;
        },
        _ => {},
        false
      );
    },
    loadTopic() {
      this.loading = true;
      var param = {};
      if (this.cateIds) {
        param = { cate: this.cateIds };
      }
      this.$http.get(
        '/exam/admin/question/topic/choose/list',
        {
          ...this.search,
          ...this.paginate,
          ...param
        },
        response => {
          this.response = response;
          this.loading = false;
        },
        _ => {
          this.loading = false;
        },
        false
      );
    },
    checkSelectable(row) {
      let result = true;
      this.parts.forEach(part => {
        if (part.topics.findIndex(item => item.topic.id == row.id) !== -1) {
          result = false;
          return false;
        }
      });

      return result;
    },
    handleCurrentChange: function(page) {
      this.paginate.page = page;
      this.loadTopic();
    },
    // 单行选中与取消事件
    handleSelectChange: function(selection) {
      this.topics = selection;
    }
  }
};
</script>

<style></style>
